import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class FileServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取下载文件的路径
        //String realPath = this.getServletContext().getRealPath("/1.jpg");
        String realPath = ("C:\\Code\\JavaWeb\\Servlet_03\\src\\main\\resources\\文件下载");

        System.out.println("下载的文件路径为：" + realPath);
     //2.下载的文件名
        String Filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
    //3.设置浏览器能够支持下载我们需要的东西
        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(Filename, "utf-8"));
    //4.获取下载文件输入流
        FileInputStream fileInputStream = new FileInputStream(realPath);
    //5.创建缓冲区
        int length = 0;
        byte[] buffer = new byte[1024];
    //6.获取OutputStream流
        ServletOutputStream outputStream = resp.getOutputStream();
    //7.将获取的FileOutputStream流写入到缓冲区
        while ((length = fileInputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
        fileInputStream.close();
        outputStream.close();
//8.使用缓冲区的数据写到本地客户端
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
